package demo1.StrategyPattern;

/**
 * @ClassName StrategyPattern
 * @Description TODO
 * @Author 耀酱
 * @Date 2023/6/4 15:04
 * @Version 1.0
 */
// 策略模式

// 假设你正在编写一个电商网站，并需要计算每个订单的折扣费用。你可以使用策略模式来实现这个功能
public class StrategyPattern {
    public static void main(String[] args) {
        // 创建对象可以用工厂来执行 具体策略应该被封装
        DiscountStrategy discountStrategy = new CashbackDiscountStrategy(0.5); // 五折策略
        DiscountStrategy discountStrategy1 = new PercentDiscountStrategy(0.5); // 一折策略

        Order order = new Order(100);
        order.setDiscountStrategy(discountStrategy);
        double v = order.calculateTotalPrice();
        System.out.println(v);  // 五折后的价格

        order.setDiscountStrategy(discountStrategy1);
        double v1 = order.calculateTotalPrice();
        System.out.println(v1);  // 一折后的价格

    }
}

interface DiscountStrategy{
    double calculateDiscount(double totalPrice);
}
// 打折策略一
class PercentDiscountStrategy implements DiscountStrategy{
    private double discountPercent;

    public PercentDiscountStrategy(double discountPercent) {
        this.discountPercent = discountPercent;
    }

    @Override
    public double calculateDiscount(double totalPrice) {
        return discountPercent * totalPrice;
    }
}
//打折策略二
class CashbackDiscountStrategy implements DiscountStrategy{
    private double cashbackAmount;
    public CashbackDiscountStrategy(double cashbackAmount) {
        this.cashbackAmount = cashbackAmount;
    }
    @Override
    public double calculateDiscount(double totalPrice) {
        return cashbackAmount * totalPrice;
    }
}

class Order {
    private double totalPrice; // 原价
    private DiscountStrategy discountStrategy;  // 打折策略的抽象接口

    public Order(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public void setDiscountStrategy(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    /**
     *  计算 折扣后的价格
     * @return
     */
    public double calculateTotalPrice() {
        return totalPrice - discountStrategy.calculateDiscount(totalPrice);
    }
}